<template>
  <div class="register-page">
    <van-nav-bar 
      title="注册" 
      left-text="返回"
      left-arrow
      @click-left="router.back()"
    />
    
    <div class="register-form">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field
            v-model="formData.username"
            name="username"
            label="用户名"
            placeholder="请输入用户名"
            :rules="[{ required: true, message: '请填写用户名' }]"
          />
          <van-field
            v-model="formData.password"
            type="password"
            name="password"
            label="密码"
            placeholder="请输入密码"
            :rules="[{ required: true, message: '请填写密码' }]"
          />
          <van-field
            v-model="formData.name"
            name="name"
            label="姓名"
            placeholder="请输入姓名"
          />
          <van-field
            v-model="formData.email"
            name="email"
            label="邮箱"
            placeholder="请输入邮箱"
            :rules="[
              { required: true, message: '请填写邮箱' },
              { pattern: /.+@.+\..+/, message: '请输入正确的邮箱格式' }
            ]"
          />
        </van-cell-group>
        
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit">
            注册
          </van-button>
          <van-button 
            round 
            block 
            plain 
            type="primary" 
            style="margin-top: 10px;"
            @click="router.push('/login')"
          >
            已有账号，去登录
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive } from 'vue';
import { useRouter } from 'vue-router';
import { showToast } from 'vant';
import { userApi } from '@/api';
import type { RegisterParams } from '@/api/types';

const router = useRouter();

const formData = reactive<RegisterParams>({
  username: '',
  password: '',
  name: '',
  email: ''
});

const onSubmit = async () => {
  try {
    await userApi.register(formData);
    showToast('注册成功');
    router.push('/login');
  } catch (error: any) {
    showToast(error.response?.data?.message || '注册失败');
  }
};
</script>

<style scoped>
.register-page {
  min-height: 100vh;
  background-color: #f7f8fa;
}

.register-form {
  padding: 20px;
}

.van-cell-group {
  margin-top: 20px;
}
</style>
